import {
    HANDLERS
} from "./websocketUtil.js"
layui.use(['element', 'layer', 'util'], function () {
    var element = layui.element
        , layer = layui.layer
        , util = layui.util
        , $ = layui.$;
    //头部事件
    util.event('lay-header-event', {
        //左侧菜单事件
        menuLeft: function (othis) {
            layer.msg('展开左侧菜单的操作', {icon: 0});
        }
        , menuRight: function () {
            layer.open({
                type: 1
                , content: '<div style="padding: 15px;">处理右侧面板的操作</div>'
                , area: ['260px', '100%']
                , offset: 'rt' //右上角
                , anim: 5
                , shadeClose: true
            });
        }
    });
});
/*导生表加载*/
let uID = $("#uID").html()
localStorage.setItem("cancel","true")
var tableIns = layui.use('table', function () {
    var table = layui.table;
    table.render({
        elem: '#guiders',
        height: 500,
        url: gOptions.defaultURLPrefix+'/yewen/search/byEduCounselorMajor',
        method: "post",
        where: {
            eduCounselorMajor: "ALL"
        },
        cols: [[ //表头
            {field: 'guiderPro', title: '专业', width: 160, align: 'center'}
            , {field: 'guiderName', title: '导生名', width: 160, align: 'center'}
            , {field: 'state', title: '状态', width: 80, sort: true, align: 'center'}
            , {field: 'operation', title: '操作', width: 340, align: 'center'}
        ]],
        parseData: function (res) {
            let data = res.data;
            const length = data.length;
            let i = 0;
            for (const item of data) {
                if (item.guiderName === uID) {
                    data.splice(i, 1);
                }
                i++;
            }
            for (let i = 0; i < data.length; i++) {
                if (data[i].state === true) {
                    data[i].operation = "<li>" +
                        "<button class='operationButton'>留言</button>" +
                        "<button class='operationButton' onclick='chat(this)'>咨询</button>" +
                        "</li>"
                    data[i].state = "<embed src=\"../../images/onlineIcon.svg\" type=\"image/svg+xml\"/>"
                } else {
                    data[i].state = "<embed src=\"../../images/outlineIcon.svg\" type=\"image/svg+xml\"/>"
                    data[i].operation = "<li>" +
                        "<button class='operationButton'>留言</button>" +
                        "</li>"
                }
                /*导生状态在线*/
            }
            return {
                "code": res.code,
                "msg": res.msg,
                "count": res.count,
                "data": res.data
            }
        }
    });
});

let targetID;
let ws;
export let waitingLayer;

// ws连接配置
if ('WebSocket' in window) {
    ws = new WebSocket("ws://"+gOptions.serverAddress+":"+gOptions.port+"/ws?userID=" + uID+"&token="+localStorage.getItem("token"));

    //连接发生错误的回调方法
    ws.onerror = function (e) {
        console.log("WebSocket连接发生错误，原因为" + e)
    };
    //连接成功建立的回调方法
    ws.onopen = function () {
        console.log("客户端WebSocket连接成功");
    };
    //接收到消息的回调方法
    ws.onmessage = function (event) {
        let messageJSON = JSON.parse(event.data);
        let type = messageJSON.type;
        let handler = HANDLERS.get(type)
        handler(ws,messageJSON);
    }

    //连接关闭的回调方法
    ws.onclose = function (e) {
        console.log("ws连接已关闭，信息如下" + e.code + e.reason + e.wasClean);
    }
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        ws.close();
    }
} else {
    alert('当前浏览器不支持本网站！')
}

export function openChatBox(title) {
    targetID = title;
    let $chatBox = $('<div/>', {"id": "chatBox"});
    let $messageShowBox = $('<div/>', {
        "id": "messageShowBox"
    });
    let $messageInputBox = $('<div/>', {"id": "messageInputBox"});
    let $additionalTools = $('<div/>', {"id": "additionalTools"});
    let $messageInput = $('<textarea/>', {
        "id": "messageInput",
        "wrap": "physical",
        "onkeydown":"keyDownSend(event,this)"
    });
    let $sendButton = $('<button/>', {
        "class": "layui-btn",
        "onclick": "sendMsg(this)"
    });
    $chatBox.append($messageShowBox);
    $chatBox.append($messageInputBox);
    $messageInputBox.append($additionalTools);
    $messageInputBox.append($messageInput);
    $messageInputBox.append($sendButton);
    $sendButton.html("发送");
    layui.use('layer', function () {
        let layer = layui.layer;
        layer.open({
            type: 1,
            closeBtn: 2,
            maxmin: true,
            resize: false,
            title: [title, "font-size:18px;text-align:center;"],
            area: ['893px', '600px'],
            scrollbar: false,
            content: $chatBox[0].outerHTML,
            cancel: function(index, layero){
                layer.close(index);
                localStorage.setItem("cancel","true")
            }
        })
    })
}
window.keyDownSend = function(event,textarea){
    if (event.keyCode===13&&!event.shiftKey){
        let $button = $(textarea).next();
        sendMsg($button)
        event.preventDefault();
    }
}

window.sendMsg = function(button) {
    // let myMessage = $('#messageInputBox textarea').val();
    let myMessage = $(button).prev().val();
    let messageShowBox = $(button).parent().prev();
    // const messageShowBox = $("#messageShowBox");
    let toUser = $(button).parent().parent().parent().prev().html();
    let messageJSON = {
        "type":"SEND_TO_ONE_MESSAGE",
        "body":{
            "toUser":toUser,
            "msgID":"123123",
            "content":myMessage,
            "fromUser":uID
        }
    };
    let messageObj = $('<div/>', {'class': 'myMessage'});
    messageObj.html(myMessage);
    let timeObj = $('<div/>', {'class': 'myMessage'});
    timeObj.html(new Date().toLocaleTimeString()+" "+uID);
    messageShowBox.append(timeObj);
    messageShowBox.append(messageObj);
    let sendToOneMessageHandler = HANDLERS.get("SEND_TO_ONE_MESSAGE");
    sendToOneMessageHandler(ws,messageJSON)
    $(button).prev().val('')
}

//学生发起聊天请求
window.chat=function(obj) {
    /*等待层：等待询问对应导生是否同意聊天*/
    layui.use("layer", function () {
        const layer = layui.layer;
        waitingLayer = layer.open({
            type: 1,
            title:"等待导生回复中...",
            shadeClose: true,
            // content:"等待导生回复...",
            end: function () {
                if (localStorage.getItem("cancel") === "true") {
                    layer.msg("已取消请求");
                }
                localStorage.setItem("cancel","true")
            }
        })

    })
    targetID = obj.parentElement.parentElement.parentElement.parentElement.children[1].querySelector('div').innerHTML;
    const message = {
        type:"STUDENT_TO_EDU_COUNSELOR_NOTICE",
        body:{
            toUser:targetID,
            msgID:"123123",
            content:"REQUEST_CHAT"
        }
    }
    HANDLERS.get("STUDENT_TO_EDU_COUNSELOR_NOTICE")(ws,message)
}

/**
 * 重载导生表格
 */
window.searchByMajor = function() {
    layui.use('table', function () {
        layui.table.reload('guiders', {
            where: {
                "eduCounselorMajor": $('#searchGuidersBox>input').val()
            }
        })
    })
}
